import sys
import openpyxl
from openpyxl.styles import Alignment


def create_multiplication_table(n):
    # 创建一个新的工作簿和工作表
    workbook = openpyxl.Workbook()
    sheet = workbook.active

    # 设置单元格的对齐方式
    alignment = Alignment(horizontal='center', vertical='center')

    # 填充乘法表
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            product = i * j
            sheet.cell(row=i, column=j, value=product).alignment = alignment

    return workbook


if __name__ == '__main__':
    # 从命令行接受数字 N
    if len(sys.argv) > 1:
        try:
            N = int(sys.argv[1])
            if N <= 0:
                raise ValueError
        except ValueError:
            print("请输入一个正整数 N。")
            sys.exit(1)
    else:
        print("请输入一个正整数 N。")
        sys.exit(1)

    # 创建乘法表
    workbook = create_multiplication_table(N)

    # 保存工作簿
    workbook.save(f'multiplication_table_{N}x{N}.xlsx')
